import type {
    T_Xme_NetworkProtocolName1,
    T_Xme_NetworkHostConfig_Unresolved,
    T_Xme_NetworkHost,
} from '@xinmier/lei-xing--tong-yong'

export function evaluateFullHost<
    _T_Protocol extends T_Xme_NetworkProtocolName1 = T_Xme_NetworkProtocolName1
>(
    hostConfig: null | T_Xme_NetworkHostConfig_Unresolved<_T_Protocol>,
    hostDefaultconfig: T_Xme_NetworkHostConfig_Unresolved<_T_Protocol>
): T_Xme_NetworkHost<_T_Protocol> {
    if (!hostConfig && !hostDefaultconfig) {
        throw new TypeError('[evaluateFullHost]: Invalid T_Xme_NetworkHost Configuration.')
    }

    const _hostConfig = hostConfig || hostDefaultconfig

    const protocol: undefined | _T_Protocol = _hostConfig.protocol || hostDefaultconfig.protocol
    if (!protocol || !['http:', 'https:', 'ws:', 'wss:'].includes(protocol)) {
        throw new Error('求服务器主机名： protocol 不合规。')
    }

    const nameOrIp: string = _hostConfig.nameOrIp || hostDefaultconfig.nameOrIp

    const port: undefined | string | number = _hostConfig.port || hostDefaultconfig.port

    let portNumber = typeof port === 'undefined' ? 80 : +port
    if (!(portNumber > 0)) {
        portNumber = 80
    }

    let fullHost: T_Xme_NetworkHost<_T_Protocol>['fullHost'] = `${protocol}//${nameOrIp}`

    if (
        (protocol === 'ftp:'   && portNumber !== 21 ) ||
        (protocol === 'http:'  && portNumber !== 80 ) ||
        (protocol === 'ws:'    && portNumber !== 80 ) ||
        (protocol === 'https:' && portNumber !== 443) ||
        (protocol === 'wss:'   && portNumber !== 443)
    ) {
        fullHost = `${fullHost}:${portNumber}`
    }

    return {
        fullHost,
        config: {
            protocol,
            nameOrIp,
            port: portNumber,
        },
    }
}
